package com.fsq.utils.seven7z;

import java.io.File;
import java.util.ArrayList;

public class ScanFile {

    public static ArrayList<String> scanAllFiles(String path) {
        // 用arraylist保存扫描到的路径
        File file = new File(path);
        File[] files = file.listFiles();
        String[] fileNames = file.list();
        if (fileNames == null) {
            return null;
        }
        ArrayList<String> list = new ArrayList<>(0);
        for (int i = 0; i < fileNames.length; i++) {
            if (files[i].isFile()) {
                list.add(files[i].getPath());
            } else if (files[i].isDirectory()) {
                list.addAll(scanAllFiles(files[i].getPath()));
            }
        }
        return list;
    }

    /**
     * 获取目录下指定扩展名的文件列表
     *
     * @param path       目录
     * @param extensions 扩展名
     * @return 包含指定扩展名的文件列表，如果扩展名为空，则返回目录下所有文件列表。
     */
    public static ArrayList<String> scanDirectoryByExt(String path, String... extensions) {
        if (extensions == null || extensions.length == 0) {
            return scanAllFiles(path);
        }
        File file = new File(path);
        File[] files = file.listFiles();
        String[] fileNames = file.list();
        if (fileNames == null) {
            return null;
        }
        ArrayList<String> list = new ArrayList<>(0);
        for (int i = 0; i < fileNames.length; i++) {
            if (files[i].isFile()) {
                if (endsWith(files[i].getName(), extensions))
                    list.add(files[i].getPath());
            } else if (files[i].isDirectory()) {
                list.addAll(scanDirectoryByExt(files[i].getPath(), extensions));
            }
        }
        return list;
    }

    /**
     * 是否以指定扩展名结尾
     *
     * @param fileName   文件名
     * @param extensions 扩展名
     * @return
     */
    public static boolean endsWith(String fileName, String... extensions) {
        if (extensions == null || extensions.length == 0)
            return false;
        for (String extension : extensions) {
            if (fileName.toLowerCase().endsWith(extension.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) throws Exception {
        ArrayList<String> arrayList = scanAllFiles("f:/hx1/1/");
        for (String string : arrayList) {
            System.out.println(string);
        }
//		String img = "";
//		for (int i = 0; i < arrayList.size(); i++) {
//			img = arrayList.get(i);
//			System.out.println(img);
//			if (i == 4) {
//				throw new NullPointerException();
//			}
//		}
    }
}
